<template>
  <div class="user">
    <div style="display: flex;justify-content: space-between;">
      <div>
        <el-button size="medium" type="primary" plain @click="add">添加用户</el-button>
      </div>
      <!-- 条件搜索 -->
      <div style="display: flex;">
        <el-input v-model="nickName" placeholder="按姓名或手机号搜索"
                  @change="initTable()">
        </el-input>
        <el-select v-model="roleId" placeholder="按角色类型搜索" value-key="id"
                   style="margin-left: 10px;width: 300px;" @change="initTable()">
          <el-option v-for="item in roleOptions" :key="item.id" :label="item.nameZh"
                     :value="item.id" :disabled="item.enabled != 1">
          </el-option>
        </el-select>
        <el-button style="margin-left: 10px;" @click="restData" v-debounce>
          重置
        </el-button>
      </div>
    </div>
    <div class="user-table">
      <el-table :data="tableData" v-loading="loading" border stripe style="width: 100%"
                height="100%">
        <el-table-column prop="i" label="序号" fixed="left" width="80">
        </el-table-column>
        <el-table-column prop="nickName" label="姓名" fit>
          <template slot-scope="scope">
            <span v-if="scope.row.nickName === null">微信用户</span>
            <span v-else>{{scope.row.nickName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" fit>
          <template slot-scope="scope">
            <span v-if="scope.row.phone === null">未设置</span>
            <span v-else>{{scope.row.phone}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.sex === 0">男</span>
            <span v-else-if="scope.row.sex === 1">女</span>
            <span v-else>未设置</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" show-overflow-tooltip fit>
          <template slot-scope="scope">
            <el-tag>
              {{ roleTo(scope.row.roleId) }}
              <!-- {{ item }} -->
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag size="small" type="success" v-if="scope.row.state == 1">
              在职
            </el-tag>
            <el-tag size="small" type="danger" v-else>离职</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="editUser(scope.row)" type="text" size="small">
              编辑
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button @click="deleteUser(scope.row)" type="text" size="small">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加/修改用户对话框 -->
    <el-dialog
        :visible.sync="dialogVisible"
        width="50%"
        :show-close="false"
        :title="dialogTitle"
        @close="reset"
    >
      <el-form
          :model="userForm"
          :rules="rules"
          ref="userForm"
          label-width="100px"
          class="demo-ruleForm"
      >
        <!--        <el-form-item label="工号" prop="empno">
                  <el-input
                    placeholder="请输入员工工号"
                    v-model="userForm.empno"
                  ></el-input>
                </el-form-item> -->
        <el-form-item label="姓名" prop="nickName">
          <el-input
              placeholder="请输入姓名"
              v-model="userForm.nickName"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="userForm.id == null" label="密码" prop="password">
          <el-input
              show-password
              placeholder="请输入密码"
              v-model="userForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
              placeholder="请输入手机号"
              v-model="userForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select style="width: 100%" v-model="userForm.sex" placeholder="请选择性别">
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
              style="width: 100%"
              v-model="userForm.roleId"
              placeholder="请选择角色类型">
            <el-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.nameZh"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="userForm.roleId === 3 || userForm.roleId === 7"
                      label="提成点" key="percentage">
          <el-input v-model="userForm.percentage" placeholder="请输入提成点(按百分比计算,0.1=10%)" type="number"
                    @input="inputCheck" step="0.01">
          </el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="userForm.id !== null">
          <el-button type="primary" size="small" plain @click="resetPassword" v-debounce>
            重置
          </el-button>
          <span style="margin-left: 5px;">(重置的密码为该账号手机号后四位)</span>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="userForm.state">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBtnDialog('userForm')" v-debounce>
			确 定
		</el-button>
        <el-button @click="cancleBtn">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import user from "../../api/user.js";
import userApi from "../../api/user.js"
export default {
  name: "User",
  components: {},
  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 50,
      total: 0,
      nickName: null,
      roleId: null,
      //表格数据
      tableData: [],
      //是否展示对话框
      dialogVisible: false,
      //对话框标题
      dialogTitle: "",
      //对话框表单数据
      userForm: {
        id: null,
        roles: new Array(),
        state: 1,
        percentage: 0,
      },
      //表单校验规则
      rules: {
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        nickName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" },
          {pattern: /^[1][3-9][0-9]{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
      },
      userForm2: {
        nickName: "",
        empno: "",
        password: "",
        roleId: "",
        state: "",
        phone: "",
        percentage: "",
      },
      //角色选择列表
      roleOptions: [],
    };
  },
  created() {
    this.initTable();
    //获取角色列表
    this.initRoleList();
  },

  methods: {
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.initTable()
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage
      this.initTable()
    },
    //添加用户按钮
    add() {
      this.dialogTitle = "添加用户";
      this.dialogVisible = true;
      this.userForm.roles = this.deepCopy([]);
    },

    //角色选择器
    roleTo(is) {
      //console.log("is==>",is);
      //console.log("===>",this.roleOptions)
      for (let i = 0; i < this.roleOptions.length; i++) {
        if (this.roleOptions[i].id == is) {
          return this.roleOptions[i].nameZh;
        }
      }
    },

    //编辑按钮
    editUser(data) {
      this.dialogVisible = true;
      this.dialogTitle = "编辑用户信息";
      this.userForm = data;
    },

    //对话框取消按钮
    cancleBtn() {
      this.dialogVisible = false;
      this.reset();
    },
    //重置表单
    reset() {
      this.userForm = {
        id: null,
        roles: new Array(),
        state: 1,
        percentage: 0,
      };
      this.userForm.state = 1
    },
    //表单提交
    submitBtnDialog(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("data", JSON.stringify(this.userForm));
          if (this.userForm.id == undefined) {
            this.userForm2.nickName = this.userForm.nickName;
            this.userForm2.sex = this.userForm.sex;
            this.userForm2.password = this.userForm.password;
            this.userForm2.roleId = this.userForm.roleId;
            this.userForm2.state = this.userForm.state;
            this.userForm2.phone = this.userForm.phone;
            this.userForm2.percentage = this.userForm.percentage;
            console.log(this.userForm2);

            this.$axios
                .post("/user/adminAddUser", this.userForm2)
                .then((res) => {
                  //弹窗提示
                  this.$message({
                    type: "success",
                    message: res.message,
                  });
                  if (res.code === 200) {
                    this.initTable();
                    this.dialogVisible = false;
                    this.reset();
                  }
                });
          } else {
            userApi.updateUser(this.userForm).then(res =>{
              if (res.code === 200){
                this.initTable();
                this.dialogVisible = false;
                this.reset();
              }
            })
          }
        }
      });
    },

    //删除用户
    deleteUser(data) {
      this.$confirm("是否删除用户：[ " + data.nickName + " ] 的所有信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userApi.deleteUser(data).then(res =>{
          if (res.code === 200){
            this.$message.success("删除成功");
            this.initTable();
          }
        })
        // this.$axios.post("/sysUser/delete", { id: data.id }).then((res) => {
        //   if (res.status) {
        //     this.initTable();
        //   }
        // });
      });
    },
    // //密码重置
    // resetPassword(user) {
    //   this.$axios
    //     .post("/sysUser/reset", {
    //       id: user.id,
    //     })
    //     .then((resp) => {
    //       if (resp && resp.data.code === 200) {
    //         this.$alert("密码已重置为 123");
    //       }
    //     });
    // },

    //初始化table数据
    initTable() {
      this.loading = true
      const data ={
        nickName: this.nickName,
        roleId: this.roleId,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
      }
      userApi.fuzzyQuery(data).then(res =>{
        if (res.code === 200){
          this.tableData = res.data.userVoList.map((item,index) =>{
            item.i = (this.currentPage - 1) * this.pageSize + index + 1
            item.roleId = parseInt(item.roleId)
            return item;
          })
          this.total = res.data.total
          this.loading = false
        }
      })
    },
    //获取所有角色列表
    initRoleList() {
      this.$axios.get("/sysRole/list").then((res) => {
        if (res.status) {
          this.roleOptions = res.data;
        }
      });
    },
    // 重置按钮
    restData(){
      this.nickName = null;
      this.roleId = null;
      this.currentPage = 1;
      this.pageSize = 50;
      this.initTable();
    },
    // 检查输入
    inputCheck(value){
      console.log("value=>",value);
      let inputNumber = parseFloat(value);
      if (inputNumber > 1 || inputNumber < 0.00) {
        inputNumber = null
      }
      // 使用正则表达式匹配小数点后两位以内的数字或整数
      let regex = /^\d+(\.\d{1,2})?$/;
      if (!regex.test(inputNumber)) {
        inputNumber = null
      }
      this.userForm.percentage = inputNumber
    },
    // 重置密码
    resetPassword(){
      this.$confirm("是否要重置该账号的密码？","提示",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() =>{
        console.log("用户点击确定")
        const data = {
          id: this.userForm.id
        }
        const loading = this.$loading({
          lock: true,
          text: '请求中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        userApi.resetPassword(data).then(res =>{
          if (res.code === 200){
            this.$message.success("重置成功");
          }
        }).finally(() =>{
          loading.close();
        })
      }).catch(() =>{
        console.log("用户点击取消")
      })
    }
  },
};
</script>

<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
<style scoped>
.user{
  height: 100%;
}

.user-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}

.block {
  text-align: right;
  margin: 10px;
}

.avatar-uploader .el-upload {
  width: 23%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: absolute;
  left: 73%;
  top: 13%;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

avatar-uploader .el-upload {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
